package xcf.data.session.defalut;

import xcf.data.model.BoundSql;
import xcf.data.model.Configuration;
import xcf.data.model.MapperStatement;
import xcf.data.session.IExecutor;
import xcf.data.utils.GenericTokenParser;
import xcf.data.utils.ParameterMapping;
import xcf.data.utils.ParameterMappingTokenHandler;
import xcf.data.utils.ReflectUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class DefaultExecutor implements IExecutor {

    @Override
    public <E> List<E> query(Configuration configuration, MapperStatement statement, Object... params) throws Exception {
        // 1.获取连接
        Connection connection = configuration.getDataSource().getConnection();
        String sqlSource = statement.getSqlSource();
        // 2.解析sql
        BoundSql boundSql = getBoundSql(sqlSource);
        // 3.预处理对象
        PreparedStatement prepare = connection.prepareStatement(boundSql.getSqlText());
        // 4.设置参数
        String paramTypeName = statement.getParamTypeName();
        Class<?> paramClass = ReflectUtils.getClass(paramTypeName);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping mapping = parameterMappings.get(i);
            String content = mapping.getContent();
            Field field = paramClass.getDeclaredField(content);
            field.setAccessible(true);
            Object filedValue = field.get(params[0]);
            prepare.setObject(i + 1, filedValue);
        }
        // 5.执行sql
        ResultSet resultSet = prepare.executeQuery();
        // 6.封装结果集
        String returnTypeName = statement.getReturnTypeName();
        Class<?> returnClass = ReflectUtils.getClass(returnTypeName);
        List<Object> list = new ArrayList<>();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object result = returnClass.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                // 使用反射和内省，设置对象字段的值
                PropertyDescriptor descriptor = new PropertyDescriptor(columnName, returnClass);
                Method writeMethod = descriptor.getWriteMethod();
                writeMethod.invoke(result, value);
            }
            list.add(result);
        }
        return (List<E>) list;
    }

    /**
     * 对#{}进行解析工作
     *
     * @param sqlSource
     * @return
     */
    private BoundSql getBoundSql(String sqlSource) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        // 解析过后的sql
        String parseSql = genericTokenParser.parse(sqlSource);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        return new BoundSql(parseSql, parameterMappings);
    }
}
